//
//  BillListDelegater.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/4/25.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit
import Alamofire

class BillListDelegater: NSObject {

    var bills:[Bill]? {
        didSet {
            self.tableView?.reloadData()
        }
    }

    weak var tableView:UITableView?

    class func delegater(with tableView:UITableView) -> BillListDelegater {
        let delegater = BillListDelegater()
        delegater.tableView = tableView
        delegater.configure()
        return delegater
    }

    func configure() -> Void {
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.tableView?.register(BillListTableCell.classForCoder(), forCellReuseIdentifier: BillListTableCell.cellIdentifier())
    }

}


extension BillListDelegater : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.bills?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = BillListTableCell.tableCell(tableView: tableView) as! BillListTableCell
        cell.configure(self.bills?[indexPath.row] as AnyObject)
        cell.delegate = self;
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return BillListTableCell.cellHeight()
    }
}

extension BillListDelegater: BillListTableCellDelegate {
    func onFavoriteButtonClick(_ button: UIButton, _ indexPath: IndexPath) {
        LGHUD.loading("")

        let bill = self.bills?[indexPath.row]
        let requestString = "http://music.baidu.com/data/music/fmlink?rate=320&songIds="+(bill?.song_id!)!+"&type=&callback=cb_download&_t=1468380564513&format=json"

        Alamofire.request(requestString).responseString { (response) in

            var string = response.value?.replacingOccurrences(of: "cb_download(", with: "")
            string =  string?.replacingOccurrences(of: "\t", with: "")
            let index = string?.index((string?.endIndex)!, offsetBy: -1)
            string = string?.substring(to: index!);
            let songs = [Song].deserialize(from: string , designatedPath: "data.songList")
            if ((songs?.count) != 0) {
                let song = songs?[0]
                SongFMDBHelper.updateSongTable(song!, isFavorite: !((bill?.isFavorite!)!), block: { (success) in
                    if success {
                        self.bills![indexPath.row].isFavorite = button.isSelected
                        if button.isSelected {
                            LGHUD.showSuccess("收藏成功")
                        }else {
                            LGHUD.showSuccess("已取消收藏成功")
                        }
                        let deadlineTime = DispatchTime.now() + .seconds(1)
                        DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
                            NotificationCenter.default.post(Notification.init(name: Notification.Name(rawValue: SM_SONG_FAVORITE_LIST_DID_CHANGE_NOTIFICATION)))
                        }
                    }else {
                        if button.isSelected {
                            LGHUD.showError("取消收藏失败")
                        } else {
                            LGHUD.showError("收藏失败")
                        }
                    }
                })
            }else {
                self.tableView?.reloadData()
                LGHUD.showError("收藏失败")
            }

        }
    }
}
